package com.example.xiaomaotv;

import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{
    private LinearLayout mainLy;
    private LinearLayout messageLy;
    private LinearLayout mineLy;
    private MainFragment mainFragment;
    private MessageFragment messageFragment;
    private  MineFragment mineFragment;
    private List<LinearLayout> tabList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);

        mainFragment = new MainFragment();
        messageFragment = new MessageFragment();
        mineFragment = new MineFragment();
        initView();//初始化控件
        tabChange(R.id.ly_main);//默认首页显示颜色
        changeFragment(mainFragment);//默认首页界面
    }
    private void initView(){
        mainLy = findViewById(R.id.ly_main);
        messageLy = findViewById(R.id.ly_message);
        mineLy = findViewById(R.id.ly_mine);
        mainLy.setOnClickListener(this);
        messageLy.setOnClickListener(this);
        mineLy.setOnClickListener(this);
        tabList.add(mainLy);
        tabList.add(messageLy);
        tabList.add(mineLy);
    }
    //点击事件，切换界面
    @Override
    public void onClick(View v) {
        int clickTabId = v.getId();
        tabChange(clickTabId);
        if (clickTabId == R.id.ly_main){
            changeFragment(mainFragment);
        } else if (clickTabId == R.id.ly_message) {
            changeFragment(messageFragment);
        }else {
            changeFragment(mineFragment);
        }
    }
    //按钮变换颜色
    private void tabChange(int clickedTabId){
        for (LinearLayout tab:tabList) {
            if (tab.getId() == clickedTabId){
                tab.setBackgroundColor(getColor(R.color.tab_checked));
            }else {
                tab.setBackgroundColor(getColor(R.color.tab_unchecked));
            }
        }
    }
    //界面变换
    private void changeFragment(Fragment fragment){
        FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        transaction.replace(R.id.layout_content,fragment);
        transaction.commit();
    }
}